import { reactive, ref } from 'vue'

export default () => {
  const move = reactive({
    top: 0,
    left: 0,
  })

  const tableHeaderRightRef = ref<HTMLElement | null>(null)
  const isTableScroll = ref<boolean>(false)
  const tableRef = ref<HTMLElement | null>(null)
  const tableRightRef = ref<HTMLElement | null>(null)
  const popupIndex = ref(-1)

  function handleTableScroll(e: Event) {
    popupIndex.value = -1
    const top = (e.target as HTMLDivElement).scrollTop
    isTableScroll.value = true
    if (top > 0 && tableHeaderRightRef.value) {
      tableHeaderRightRef.value.scrollLeft = move.left
    }
  }

  function onTableRightScroll(e: Event) {
    const left = (e.target as HTMLDivElement).scrollLeft

    move.left = left

    tableHeaderRightRef.value && (tableHeaderRightRef.value.scrollLeft = left)
  }

  function onTableHeaderScroll(e: Event) {
    if (!tableRightRef.value) return
    tableRightRef.value.scrollLeft = (e.target as HTMLElement).scrollLeft
  }

  function resetTableStatus() {
    if (tableRightRef.value) {
      tableRightRef.value.scrollLeft = 0
    }

    if (tableRef.value) {
      tableRef.value.scrollTop = 0
    }

    move.top = 0
    move.left = 0
  }

  return {
    tableHeaderRightRef,
    isTableScroll,
    tableRightRef,
    tableRef,
    popupIndex,
    handleTableScroll,
    onTableRightScroll,
    onTableHeaderScroll,
    resetTableStatus,
  }
}
